from django.shortcuts import render
from django.shortcuts import render
from django.shortcuts import render
import django_filters
from django_filters import FilterSet
from django_filters.rest_framework import DjangoFilterBackend, FilterSet
from rest_framework import viewsets
from rest_framework.decorators import action
from rest_framework.filters import OrderingFilter
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
from shop import models, serializers
# Create your views here.


class ProductViewSet(viewsets.ModelViewSet):
    queryset = models.Product.objects.all()
    serializer_class = serializers.ProductSerializer

class ShoppingViewSet(viewsets.ModelViewSet):
    queryset = models.Shopping.objects.all()
    serializer_class = serializers.ShoppingSerializer

    @action(detail=True, methods=['post'])
    def add(self,request,pk):
        print(pk)
        data = models.Shopping.objects.filter(id=pk)
        print(data)
        if data.exists():
            data = self.get_object()
            data.num += 1
            data.save()
            return Response({'message':'商品重复添加成功'})
        else:
            print(request.data)
            add = request.data.copy()
            add['num'] = 1
            print(add)
            serializer = self.get_serializer(data=add)
            if serializer.is_valid():
                serializer.save()
                return Response({'message': '添加购物车成功'})
            else:
                return Response({'message': '添加购物车失败'})
